package com.sinodata.bsm.cicp.collector.IIS6;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class WebSite extends Collector {

    private static Logger logger = Logger.getLogger(WebSite.class);
    static final String cmdStr = "iissiteinfo.exe";
    static final String regStr = "(\\S+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)";

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {

        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        String siteName = getParamMap().get("Site_Name");
        BufferedReader reader = null;
        try {
            reader = CommandReader.getReader(ip, cmdStr, 0, 0);
            String line = null;
            Pattern p = Pattern.compile(regStr);
            Matcher match = null;
            while ((line = reader.readLine()) != null) {
                match = p.matcher(line);
                if (match.matches() && line.contains(siteName)) {
                    for (int i = 0; i < propMetas.length; i++) {
                        propValues[i] = ResPropertyValue.createPropValue(match.group(i + 2), propMetas[i]);
                    }
                    propertyValueX.setValues(propValues);
                    values.add(propertyValueX);
                    return values;
                }

            }
        } catch (Exception e) {
            logger.error("collect iis6 website error", e);
            throw new CollectorException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    @Override
    public String[] getParamMeta() {
        //return new String[] { "站点名" };
        return new String[] { "Site_Name" };
    }

    @Override
    public String[] getPropMeta() {
        //return new String[] { "当前用户数", "总用户数", "每秒流量", "当前连接", "最大连接" };
        //        return new String[] { "Current_User_Count", "Total_User_Count", "Flow_Per_Second", "Current_Connection", "Max_Connection" };
        return new String[] { "$1", "$2", "$3", "$4", "$5" };
    }

}
